package com.leyou.page.service;

import com.leyou.item.pojo.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecificationClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
@Slf4j
public class PageService {

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specClient;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 获取 商品详情页 数据
     *
     * @param spuId
     * @return
     */
    public Map<String, Object> loadModel(Long spuId) {
        Map<String, Object> model = new HashMap<>();

        // spu
        Spu spu = goodsClient.querySpuById(spuId);
        // skus
        List<Sku> skus = spu.getSkus();
        // spuDetail
        SpuDetail detail = spu.getSpuDetail();
        // brand
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
        // categories
        List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
        List<Category> names = categoryClient.queryCategoryByIds(cids);
        List<Map<String, Object>> categories = new ArrayList<>();
        for (int i = 0; i < cids.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", cids.get(i));
            map.put("name", names.get(i).getName());
            categories.add(map);
        }

        // groups
        List<SpecGroup> groups = specClient.queryGroupByCid(spu.getCid3());

        // 查询特殊的规格参数
        List<SpecParam> params = new ArrayList<>();
        for (SpecGroup group : groups) {
            group.getParams().forEach(param -> {
                if (!param.getGeneric()) {
                    // 是特殊参数
                    params.add(param);
                }
            });
        }

        // 初始化特殊规格参数的map
        Map<Long, String> paramMap = new HashMap<>();
        params.forEach(param -> {
            paramMap.put(param.getId(), param.getName());
        });

        model.put("spu", spu);
        model.put("skus", skus);
        model.put("spuDetail", detail);
        model.put("brand", brand);
        model.put("categories", categories);
        model.put("groups", groups);
        model.put("paramMap", paramMap);

        return model;
    }

    /**
     * 生成静态 HTML 文件
     */
    public void createHtml(Long spuId) {
        // Context
        Context context = new Context();
        context.setVariables(loadModel(spuId));

        // 输出流
        File dest = new File("F:\\leyou\\upload", spuId + ".html");

        // 删除已存在的静态页
        if (dest.exists()) {
            if (dest.delete()) {
                log.info("[静态页服务] 删除旧文件 " + dest.getName() +" 成功！");
            }
        }

        try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
            // 生成 HTML
            templateEngine.process("item", context, writer);
            log.info("[静态页服务] 新建文件 " + dest.getName() +" 成功！");
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            log.error("[静态页服务] 生成静态页异常！", e);
        }
    }

    public void deleteHtml(Long spuId) {
        // 输出流
        File dest = new File("F:\\leyou\\upload", spuId + ".html");

        if (dest.exists()) {
            if (dest.delete()) {
                log.info("[静态页服务] 删除旧文件 " + dest.getName() +" 成功！");
            }
        }
    }
}
